import constant from './constant'

// 存储变量名
let storageKey = 'storage_data'

// 存储节点变量名
let storageNodeKeys = [constant.token, constant.avatar, constant.id, constant.name, constant.roles, constant.permissions, constant.routers]

const storage = {
  set: function(key, value) {
    if (storageNodeKeys.indexOf(key) != -1) {
      try {
        let tmp = uni.getStorageSync(storageKey)
        tmp = tmp ? tmp : {}
        tmp[key] = value
        uni.setStorageSync(storageKey, tmp)
      } catch (error) {
        console.error(`存储 ${key} 失败:`, error)
      }
    }
  },
  get: function(key) {
    try {
      let storageData = uni.getStorageSync(storageKey) || {}
      let value = storageData[key]
      
      // 处理默认值，确保数组类型的键返回数组
      if (value === undefined || value === null) {
        const arrayKeys = [constant.roles, constant.permissions, constant.routers]
        if (arrayKeys.includes(key)) {
          value = []
        } else {
          value = ""
        }
      }
      
      return value
    } catch (error) {
      console.error(`获取 ${key} 失败:`, error)
      // 根据键类型返回合适的默认值
      const arrayKeys = [constant.roles, constant.permissions, constant.routers]
      if (arrayKeys.includes(key)) {
        return []
      }
      return ""
    }
  },
  remove: function(key) {
    try {
      let storageData = uni.getStorageSync(storageKey) || {}
      delete storageData[key]
      uni.setStorageSync(storageKey, storageData)
    } catch (error) {
      console.error(`删除 ${key} 失败:`, error)
    }
  },
  clean: function() {
    try {
      uni.removeStorageSync(storageKey)
    } catch (error) {
      console.error('清理存储失败:', error)
    }
  }
}

export default storage
